package com.lcc.bank.tools.base.aspect;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.lcc.bank.tools.base.bean.ResultContext;
import com.lcc.bank.tools.base.enums.ENMsgCode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author lincc
 * @version 1.0  2018/11/27
 */
@Aspect
@Component
public class SystemAspect {

    @Around("execution(* com.lcc.bank.tools.controller..*.*(..))")
    public Object exceptionHandle(ProceedingJoinPoint pjp) {
        ResultContext resultContext = new ResultContext();
        Logger logger = LoggerFactory.getLogger(pjp.getTarget().getClass());
        String signatureName = pjp.getSignature().getName();
        String entryParameter = "方法" + signatureName +
                "请求参数：" +
                JSONUtil.toJsonStr(pjp.getArgs());
        logger.info(entryParameter);
        try {
            resultContext = (ResultContext) pjp.proceed();
            //下载文件等不需要返回值的特殊处理
            if (ObjectUtil.isNull(resultContext)) {
                return null;
            }
            if (resultContext.getSuccess() == null && resultContext.getCode() == null) {
                resultContext.setSuccess(true);
                resultContext.setCode(ENMsgCode.SUCCESS.getValue());
            } else if (resultContext.getSuccess() == null || resultContext.getCode() == null) {
                throw new RuntimeException("success|code返回结果有误！");
            }
            if (StrUtil.isBlank(resultContext.getInfo())) {
                resultContext.setInfo("操作成功！");
            }
            return resultContext;
        } catch (Throwable throwable) {
            logger.error("执行发生异常",throwable);
            resultContext = new ResultContext<>();
            resultContext.setSuccess(false);
            resultContext.setCode(ENMsgCode.SYSTEM_EXCEPTION.getValue());
            resultContext.setInfo(ENMsgCode.SYSTEM_EXCEPTION.getLabel());
            return resultContext;
        } finally {
            String logStr = ObjectUtil.isNotNull(resultContext) ? JSONUtil.toJsonStr(resultContext) : "不打印";
            logger.info("方法{}返回结果：{}", pjp.getSignature().getName(), logStr);

        }
    }

}
